<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class UploadController extends Controller
{
  /**
   * 单图上传
   * @param Request $request
   * @return string
   */
  public function upload($model)
  {
    $file = Input::file('file');
    try {
      if ($file->isValid()) {
        $entension = $file->getClientOriginalExtension(); //上传文件的后缀.
        $newName = getMemberId() . "." . $entension;
        $path = $this->SymbolSwitch($file->move('uploads/' . $model, $newName));
        return $this->uploadMsg(0, '文件上传成功', asset($path));
      } else {
        return $this->uploadMsg(1, '上传失败,请刷新重试');
      }
    } catch (\Exception $error) {
      return $this->uploadMsg(1, '上传失败,请刷新重试');
    }
  }

  /**
   * layui 图片上传放回
   * @param $status
   * @param string $message
   * @param array $data
   * @return \Illuminate\Http\JsonResponse
   */
  public function uploadMsg($status, $message = '', $data = array())
  {
    $result = array(
        'code' => $status,
        'message' => $message,
        'data' => $data
    );
    return response()->json($result);
  }

  /**
   * laravel图片路径转换
   * @param $data
   * @return mixed
   */
  public function SymbolSwitch($data)
  {
    return str_replace('\\', '/', $data);
  }
}
